#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QTime>
#include <QString>
#include <QIcon>
#include <QPushButton>

// the timer; figure moves down one square with each second
QTimer *timer;
const int WIDTH = 10, HEIGHT = 18;
const int NEXTWIDTH = 4;
TetrisSquare *currentSquare;
int xCoord = 5, yCoord = 0;

// the 2D array of squares that comprise the game board
TetrisSquare *field[HEIGHT][WIDTH];
TetrisSquare *nextField[NEXTWIDTH][NEXTWIDTH];

TetrisSquare::TetrisSquare(QPushButton *parent) : QPushButton(parent)
{
   //color
}


TetrisSquare::~TetrisSquare(){

}

// main constructor
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // initialize the timer
    timer = new QTimer(this);

    //connect timer with updateLCD function
    connect(timer, SIGNAL(timeout()), this, SLOT(updateLCD()));



    //set spacing between blocks
    ui->tetrisLayout->setSpacing(0);
    ui->nextFigureLayout->setSpacing(0);
    int i, j;
    // fill Tetris grid with push buttons
    for (i = 0; i < HEIGHT; ++i) {
        for (j = 0; j < WIDTH; ++j) {
            field[i][j] = new TetrisSquare;
           // field[i][j]->setFixedSize(10, 10);
            // add the TetrisSquare to the layout

           field[i][j]->setIcon(QIcon("white.jpg"));
            field[i][j]->setFlat(true);

            ui->tetrisLayout->addWidget(field[i][j], i, j);

            // connect the signals and slots
            //connect(field[i][j], SIGNAL(clicked()), this, SLOT(squareClicked()));
        }
    }

    //create a grid for displaying the next figure
    for (i = 0; i < NEXTWIDTH; ++i) {
        for (j = 0; j < NEXTWIDTH; ++j) {
            nextField[i][j] = new TetrisSquare;
            ui->nextFigureLayout->addWidget( nextField[i][j], i, j);
        }
    }
   // field[3][3]->setIcon(QIcon(QString(":/images/blue.jpg").toAscii()));

   // field[3][3]->setIcon(QIcon("blue.jpg"));

    //timer will timeout in 1 sec
    timer->start(500);
    currentSquare = field[yCoord][xCoord];
    currentSquare->setIcon(QIcon("blue.jpg"));
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::on_actionQuit_triggered()
{
    this->close();
}

void MainWindow::updateLCD()
{
    // update the timer display
    ui->lcdNumber->display(ui->lcdNumber->value() + 1);

    if(yCoord == 17){
        yCoord = 0;

    }
    else{
        yCoord++;
    }
    currentSquare->setIcon(QIcon("white.jpg"));
    currentSquare = field[yCoord][xCoord];
     currentSquare->setIcon(QIcon("blue.jpg"));


}
